package cn.com.idmy.auth.context;

import cn.com.idmy.auth.exception.AuthException;
import cn.com.idmy.base.model.NameValue;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.jetbrains.annotations.NotNull;

import java.util.Collection;

@AllArgsConstructor
public class ResponseForServlet implements Response {
    protected final HttpServletResponse response;

    @Override
    public @NotNull Object source() {
        return response;
    }

    @Override
    public @NotNull Response status(int status) {
        response.setStatus(status);
        return this;
    }

    @Override
    public @NotNull Response setHeader(@NotNull String name, @NotNull String value) {
        response.setHeader(name, value);
        return this;
    }

    @Override
    public @NotNull Response addHeader(@NotNull String name, @NotNull String value) {
        response.addHeader(name, value);
        return this;
    }

    @Override
    public void redirect(@NotNull String url) {
        try {
            response.sendRedirect(url);
        } catch (Exception e) {
            throw new AuthException(e);
        }
    }

    @Override
    public @NotNull Collection<String> headerNames() {
        return response.getHeaderNames();
    }

    @Override
    public @NotNull Collection<String> headerValues() {
        return headerNames().stream().map(response::getHeader).toList();
    }

    @Override
    public @NotNull Collection<NameValue<String>> headers() {
        return headerNames().stream().map(name -> new NameValue<>(name, response.getHeader(name))).toList();
    }
}
